package com.mobilezu.mobile.pushserver.service.impl;

import java.util.List;

import javax.persistence.EntityExistsException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataIntegrityViolationException;

import com.mobilezu.mobile.pushserver.dao.PushUserDao;
import com.mobilezu.mobile.pushserver.model.PushUser;
import com.mobilezu.mobile.pushserver.service.PushUserService;
import com.mobilezu.mobile.pushserver.service.UserExistsException;
import com.mobilezu.mobile.pushserver.service.UserNotFoundException;


public class PushUserServiceImpl implements PushUserService {

	protected final Log log = LogFactory.getLog(getClass());

	private PushUserDao pushUserDao;

	public void setPushUserDao(PushUserDao pushUserDao) {
		this.pushUserDao = pushUserDao;
	}

	public PushUser getPushUser(String pushUserId) {
		return pushUserDao.getPushUser(new Long(pushUserId));
	}

	public List<PushUser> getPushUsers() {
		return pushUserDao.getPushUsers();
	}

	public PushUser savePushUser(PushUser pushUser) throws UserExistsException {
		try {
			return pushUserDao.savePushUser(pushUser);
		} catch (DataIntegrityViolationException e) {
			e.printStackTrace();
			log.warn(e.getMessage());
			throw new UserExistsException("User '" + pushUser.getUsername()
					+ "' already exists!");
		} catch (EntityExistsException e) { // needed for JPA
			e.printStackTrace();
			log.warn(e.getMessage());
			throw new UserExistsException("User '" + pushUser.getUsername()
					+ "' already exists!");
		}
	}

	@SuppressWarnings("finally")
	public PushUser getPushUserByUsername(String pushUsername) {
		PushUser returnUser = null;
		try {
			returnUser = (PushUser) pushUserDao
					.getPushUserByUsername(pushUsername);
		} catch (UserNotFoundException e) {
			log.warn("Username '" + pushUsername + "' not found");
		} finally {
			return returnUser;
		}
	}

	public void removePushUser(Long pushUserId) {
		log.debug("removing pushUser: " + pushUserId);
		pushUserDao.removePushUser(pushUserId);
	}

}
